<?php

namespace co2_OS;

use co2\dev\v0_0_0 as api;

class dependency

{
	protected static
	  $db
		;
		
	public function __construct()
	
	{
	  self::$db=new api\PDO('sqlite',sysvar::get('db').'/sqlite3/conf.db');
	}
	
	public static function 
	get()
	
	{
		return self::$dependencies;
	}
	
	public static function
	add(
		array $drug,
		array $junkie
	)
	
	{
	  $msg="DEPENDENCY_ADD: Received insert signal for drug of type({$drug[0]}) named({$drug[1]}) version({$drug[2]})";
	  
	  if($drug[0]==aptitude::TYPE_APP)
	  $msg.=" channel({$drug[3]})";
	  
	  $msg.=" and junkie of type({$junkie[0]}) named({$junkie[1]}) version({$junkie[2]})";
	  
	  if($junkie[0]==aptitude::TYPE_APP)
	  $msg.=" channel({$junkie[3]})";
	  
	  log::register($msg);

    $drug=$drug[0]==aptitude::TYPE_APP
      ? aptitude::get($drug[0],$drug[1],$drug[2],$drug[3])
      : aptitude::get($drug[0],$drug[1],$drug[2]);
      
    if(!count($drug))
    
    {
      log::register("DEPENDENCY_ADD: Drug not found in aptitude");
      
      throw new api\Exception('Drug not found',null,ES_PACKAGE_NOT_FOUND);
    }
    
    $drug=(int)$drug[0]->id;
    
    $junkie=$junkie[0]==aptitude::TYPE_APP
      ? aptitude::get($junkie[0],$junkie[1],$junkie[2],$junkie[3])
      : aptitude::get($junkie[0],$junkie[1],$junkie[2]);
      
    if(!count($junkie))
    
    {
      log::register("DEPENDENCY_ADD: Junkie not found in aptitude");
      
      throw new api\Exception('Junkie not found',null,ES_PACKAGE_NOT_FOUND);
    }
    
    $junkie=(int)$junkie[0]->id;
    
    if(is_null(self::$db))
	  new self;
	  
		self::$db->run("insert into dependencies values(NULL,?,?)",array($drug,$junkie));
		
		log::register("DEPENDENCY_ADD: Ok :)");
	}
	
	public static function getjunkies($drug)
	
	{
	  log::register("DEPENDENCY_GET_JUNKIES: Received search signal for junkies of drug #$drug");
	  
	  if(is_null(self::$db))
	  new self;
	  
	  $junkies=self::$db->run("select junkie from dependencies where drug=?",array($drug))->fetchAll(\PDO::FETCH_CLASS);
	  
	  log::register("DEPENDENCY_GET_JUNKIES: Drug #$drug has ".count($junkies)." junky(ies)");
	  
	  return $junkies;
	}
	
	protected static function clean()
	
	{
		foreach(self::$dependencies as $k=>$v)
		if(!count(self::$dependencies->$k))
		unset(self::$dependencies->$k);
	}
}
